// 购物车数据action
import { del, post, get } from '@common/ajax';
import logger from '@common/logger';
import { MARKET_URL, SHOP_URL } from '@common/url';
import { SHOP_COLUMN_LOCATION } from '@constants/shop';
import { dealBagListData, toggleSelectStaus, toggleItemSelectStatus, dealBagAddActivity, toggleOtherStoreStatus,
    toggleBagSelectStatus, getBagSelectItems, calcBagProduceLength, changeProductQuantity, bagDataToReviewData } from '@biztools/shopBag';
import { MARKET_ISSUER, MARKET_SCENE } from '@constants/market';
import { reviewListToMarketList } from '@biztools/review';
import {
    GET_ONLINE_BAG_DATA,
    GET_ONLINE_BAG_WAREHOUSE_DATA,
    SET_BAG_LIST_DATA,
    GET_BAG_HOT_DATA,
    SET_BAG_PRODUCT_LENGTH,
} from '../mutationType';
import { getCartGoodsIds } from '@biztools/info';
const bag = {
    state: {
        bagData: {}, // 购物袋数据
        bagWarehouseData: {}, // 购物带仓库数据
        bagList: [],
        bagHotList: [],
        bagProductLength: 0,
    },
    mutations: {
        GET_ONLINE_BAG_DATA: (state, bagData) => {
            Object.assign(state, { bagData });
        },
        GET_ONLINE_BAG_WAREHOUSE_DATA: (state, bagWarehouseData) => {
            Object.assign(state, { bagWarehouseData });
        },
        SET_BAG_LIST_DATA: (state, bagList) => {
            Object.assign(state, { bagList });
        },
        GET_BAG_HOT_DATA: (state, bagHotList) => {
            Object.assign(state, { bagHotList });
        },
        SET_BAG_PRODUCT_LENGTH: (state, bagProductLength) => {
            Object.assign(state, { bagProductLength });
        },
    },
    actions: {
        // 获取线上购物车数据
        getOnlineShopCartData: async ({ commit, dispatch }) => {
            const res = await get(SHOP_URL.bag);
            const bagList = dealBagListData(res.cart_prods);
            logger.success('获取到的线上购物车数据为：', bagList);
            // 根据门店id分组
            commit(SET_BAG_LIST_DATA, bagList);
            commit(SET_BAG_PRODUCT_LENGTH, calcBagProduceLength(bagList));
            dispatch('getBagDiscountInfo');
        },
        // 获取购物车可用的促销活动
        getBagDiscountInfo: async ({ commit, state }) => {
            const { bagList } = state;
            // 全部数据设置为试算数据
            const _allList = bagDataToReviewData(bagList);
            if (_allList.length == 0) return;
            // 进行试算
            const res = await post(MARKET_URL.calc, {
                out_trans_no: +new Date() + '',
                trial_scene: MARKET_SCENE.cart,
                trial_issuer: MARKET_ISSUER.emall,
                out_card_id: 0,
                trial_owners: reviewListToMarketList(_allList),
            });
            // const res = await get(MARKET_URL.activity, {
            //     issuer: MARKET_ISSUER.emall,
            //     use_scene: MARKET_SCENE.cart,
            //     with_item_category_confs: false,
            //     with_item_confs: true,
            // });
            logger.debugger('Bag => 获取的优惠信息为', res);
            commit(SET_BAG_LIST_DATA, dealBagAddActivity(bagList, res.data.owners));
        },
        // // 获取购物车库存信息
        // getOnlineShopCartInfo: async ({ commit, state }, { addressInfo, isMain }) => {
        //     const { bagData } = state;
        //     logger.info('ShopBag => 当前的购物袋数据为', bagData);
        //     const param = {
        //         lat: addressInfo.latitude,
        //         lng: addressInfo.longitude,
        //         city_code: addressInfo.city_code,
        //         cart_prods: bagData.map(item => {
        //             return {
        //                 prod_id: item.prod_id,
        //                 sku_id: item.sku_id,
        //                 store_id: item.store_id,
        //             };
        //         }),
        //         // 是否总部优先
        //         hq_first: 1,
        //     };
        //     const res = await post(urls.shopBagWarehouse, param);
        //     commit(GET_ONLINE_BAG_WAREHOUSE_DATA, res);
        //     const bagList = dealShopBagListData(bagData, res);
        //     logger.info('ShopBag => 处理后的购物袋数据为：', bagList);
        //     commit(SET_BAG_PRODUCT_LENGTH, calcBagProduceLength(bagList));
        //     commit(SET_BAG_LIST_DATA, bagList);
        // },
        // 删除下单的商品
        delOrderItems: async () => {},
        // 全选、反选购物袋所有数据
        toggleBagAll: ({ commit, state }) => {
            const tempData = state.bagList;
            commit(SET_BAG_LIST_DATA, toggleBagSelectStatus(tempData));
        },
        // 选中、取消一个分组所有的
        toggleStoreItem: ({ commit, state }, storeIndex) => {
            const tempData = state.bagList;
            logger.debugger('Bag => Store全选操作', tempData[storeIndex].prodsList);
            const resultList = toggleSelectStaus(tempData[storeIndex].prodsList);
            tempData[storeIndex].prodsList = resultList;
            const _tempData = toggleOtherStoreStatus(tempData, storeIndex);
            logger.info('ShopBag => 选中、取消store单项', _tempData);
            commit(SET_BAG_LIST_DATA, _tempData);
        },
        // 选中store商品
        toggleStoreListItem: ({ commit, state }, { storeIndex, prodsIndex, itemIndex }) => {
            const tempData = state.bagList;
            logger.info('Bag => 选中、取消 store 单项', tempData[storeIndex]);
            logger.info('Bag => 选中、取消 prodsList 单项', tempData[storeIndex].prodsList[prodsIndex]);
            const resultList = toggleItemSelectStatus(tempData[storeIndex].prodsList[prodsIndex].list, itemIndex);
            tempData[storeIndex].prodsList[prodsIndex].list = resultList;
            const _tempData = toggleOtherStoreStatus(tempData, storeIndex);
            logger.info('ShopBag => 操作后结果', _tempData);
            commit(SET_BAG_LIST_DATA, _tempData);
        },
        // 删除选中的商品
        delSelectBagItems: async ({ commit, state, dispatch }) => {
            const tempData = state.bagList;
            const arr = getBagSelectItems(tempData);

        },
        // 添加购物车物品
        addShopBagItem: async ({ state, dispatch }, item) => {
            // 判断当前商品是否已经存在，返回数量
            const { bagList } = state;
            let itemInfo = { ...item };
            logger.info('ShopBag => 当前购物车商品', bagList);
            const arr = (bagList || []).filter(temp => temp.prod_id === item.prod_id && temp.sku_id === item.sku_id);
            if (arr.length > 0) {
                itemInfo = {
                    ...item,
                    quantity: item.quantity + arr[0].quantity,
                };
            }
            // 添加到线上购物车
            logger.info('ShopBag => 添加购物车商品', itemInfo);
            const res = await post(SHOP_URL.bagChange, itemInfo);
            dispatch('getOnlineShopCartData');
            if (res) {
                return true;
            } else {
                return false;
            }
        },
        // // 减少购物车物品
        // minusShopBagItem: async () => {},
        // // 清空购物车
        // clearShopBag: async () => {},
        // // 增加线上购物车数据
        // addOnlineShopBagItem: async ({ dispatch }, itemInfo) => {
        //     const res = await post(urls.shopBagChange, {
        //         prods: [itemInfo],
        //     });
        // },
        // // 减少线上购物车数据
        // minusOnlineShopBagItem: async () => {},
        // // 清空线上购物车
        // clearOnlineShopBag: async () => {
        //     await del(urls.shopClearOnlineBag);
        // },
        // 删除线上购物车数据
        deleteOnlineShopBagData: async ({ commit, dispatch }, list) => {
            try {
                const res = await del(SHOP_URL.bagDelete, {
                    sku_ids: list.map(item => item.sku_id),
                });
                dispatch('getOnlineShopCartData');
                return res ? true : false;
            } catch (error) {
                return false;
            }
        },
        // 增加数量
        addBagItemQuantity: ({ state, dispatch }, itemInfo) => {
            const tempList = state.bagList;
            logger.info('ShopBag => 增加单项的数量', tempList);
            const upInfo = {
                ...itemInfo,
                quantity: itemInfo.quantity + 1,
            };
            dispatch('updateOnlineDataInfo', upInfo);
        },
        // 减少数量
        minusBagItemQuantity: ({ state, dispatch }, itemInfo) => {
            const tempList = state.bagList;
            logger.info('ShopBag => 减少单项的数量', tempList);
            const upInfo = {
                ...itemInfo,
                quantity: itemInfo.quantity - 1,
            };
            dispatch('updateOnlineDataInfo', upInfo);
        },
        updateOnlineDataInfo: async ({ dispatch }, item) => {
            await post(SHOP_URL.bagChange, {
                ...item,
            });
            dispatch('getOnlineShopCartData');
        },
        // 获取热门推荐
        getShopBagHotData: async ({ commit }) => {
            const goodsIds = getCartGoodsIds();
            if (goodsIds.length === 0) return;
            const res = await post(SHOP_URL.prefectureList, {
                id: 0,
                prod_ids: goodsIds,
            });
            logger.success('ShopBag => 获取的商城热门推荐', res);
            commit(GET_BAG_HOT_DATA, res.prods);
        },
    },
};

export default bag;
